<template>
  <div class="app-container">
    <div class="header" style="display: flex;justify-content: space-between;">
      <el-form :inline="true" :model="query" class="demo-form-inline">
        <el-form-item label="关键字">
          <el-input size="small" v-model="query.keyword" placeholder="用户名/姓名/手机号"></el-input>
        </el-form-item>
        <el-form-item label="操作时间">
          <el-date-picker
            v-model="queryTime"
            type="daterange"
            range-separator="至"
            start-placeholder="开始日期"
            end-placeholder="结束日期"
            value-format="yyyy-MM-dd">
          >
          </el-date-picker>
        </el-form-item>
        <el-form-item>
          <el-button type="primary" size="small" @click="onSubmit">查询</el-button>
        </el-form-item>
      </el-form>
      <div class="right">
        <el-button type="primary" size="small" @click="addUser">添加</el-button>
      </div>
    </div>

    <el-table
      v-loading="listLoading"
      :data="list"
      element-loading-text="Loading"
      border
      fit
      highlight-current-row
    >
      <el-table-column align="center" label="序号" width="95">
        <template slot-scope="scope">
          {{scope.$index+1}}
        </template>
      </el-table-column>
      <el-table-column label="用户名"  align="center" prop="username"></el-table-column>
      <el-table-column label="姓名"  align="center" prop="name"></el-table-column>
      <el-table-column label="手机"  align="center" prop="phone"> </el-table-column>
      <el-table-column label="状态"  align="center" prop="status">
        <template slot-scope="scope">
          <el-switch
            @change="changeStatus($event,scope.row)"
            v-model="scope.row.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#409eff"
            inactive-color="#ccc">
          </el-switch>
        </template>
      </el-table-column>
      <el-table-column class-name="status-col" label="创建时间" width="230" prop="createTime" align="center"></el-table-column>
      <el-table-column align="center" prop="created_at" label="操作" width="200">
        <template slot-scope="scope">
          <el-button icon="el-icon-edit" type="primary" @click=editUser(scope.row) size="mini"></el-button>
          <el-button icon="el-icon-delete" type="warning" @click="deleteUser(scope.row.id)" size="mini"></el-button>
          <el-button icon="el-icon-s-tools" type="success" @click="toAssign(scope.row)" size="mini"></el-button>
        </template>
      </el-table-column>
    </el-table>
    <el-pagination
      background
      layout="sizes,prev, pager, next"
      :page-sizes="[2,5,10,20]"
      :page-size="limit"
      @size-change="sizeChange"
      @current-change="currentChange"
      :total="total">
    </el-pagination>


    <!--    弹窗-->
    <el-dialog title="分配角色" :visible.sync="dialogRoleVisible">
      <el-form :model="roleForm" label-width="80px" label-position="left">
        <el-form-item label="用户名" >
          <el-input style="width: 90%;" v-model="roleForm.username" readonly/>
        </el-form-item>
        <el-form-item label="角色" >
          <el-checkbox :indeterminate="isIndeterminate" v-model="checkAll" @change="handleCheckAllChange">全选</el-checkbox>
          <el-checkbox-group v-model="roleForm.roleIdList" @change="handleCheckedCitiesChange">
            <el-checkbox v-for="city in allRoles" :label="city.id" :value="city.id" :key="city.id">{{city.roleName}}</el-checkbox>
          </el-checkbox-group>
        </el-form-item>
        </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogRoleVisible = false">取 消</el-button>
        <el-button type="primary" @click="doAssign">确 定</el-button>
      </div>
    </el-dialog>


    <el-dialog title="用户" :visible.sync="dialogFormVisible">
      <el-form :model="form" label-width="80px" label-position="left">
        <el-form-item label="用户名" ><el-input style="width: 90%;" v-model="form.username"  autocomplete="off"/></el-form-item>
        <el-form-item label="姓名" ><el-input style="width: 90%;" v-model="form.name" /></el-form-item>
        <el-form-item label="手机号" ><el-input style="width: 90%;" v-model="form.phone" /></el-form-item>
        <el-form-item label="密码" ><el-input style="width: 90%;" v-model="form.password" /></el-form-item>
        <el-form-item label="状态" >
          <el-switch
            v-model="form.status"
            :active-value="1"
            :inactive-value="0"
            active-color="#409eff"
            inactive-color="#ccc">
          </el-switch>
        </el-form-item>
        <el-form-item label="描述" ><el-input style="width: 90%;" type="textarea" :rows="2" v-model="form.description" /></el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button @click="dialogFormVisible = false">取 消</el-button>
        <el-button type="primary" @click="submitUser">确 定</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import api from '@/api/user'

export default {
  data() {
    return {
      list: null,
      listLoading: true,
      page:1,
      limit:10,
      query:{keyword:"",createTimeBegin:'',createTimeEnd:''},
      total:0,
      dialogFormVisible:false,
      dialogRoleVisible:false,
      multipleSelection:[],
      queryTime:"",
      roleForm:{
        "roleIdList": [],
        "userId": "",
        "username": "",
      },
      checkAll: false,
      allRoles: [],
      isIndeterminate: true,
      form:{
        username:'',
        phone:'',
        name:'',
        password:'',
        status:1,
      }
    }
  },
  created() {
    this.fetchData()
  },
  methods: {
    handleCheckAllChange(val) {
      this.roleForm.roleIdList = val ? this.allRoles.reduce((r,c)=>r.concat(c.id),[]) : [];
      this.isIndeterminate = false;
    },
    handleCheckedCitiesChange(value) {
      let checkedCount = value.length;
      this.checkAll = checkedCount === this.allRoles.length;
      this.isIndeterminate = checkedCount > 0 && checkedCount < this.allRoles.length;
    },
    async changeStatus(val, row) {
      await api.updateStatus(row.id,val);
    },
    resetForm(){
      this.form={
        username:'',
        phone:'',
        name:'',
        password:'',
        status:1,
      }
    },
    submitUser(){
      if (this.form.id){
        api.update(this.form).then(value => {
          console.log(value);
          this.$message({
            type: 'success',
            message: '修改成功!'
          });
          this.fetchData();
          this.dialogFormVisible=false;
        });
      }else {
        api.save(this.form).then(value => {
          console.log(value);
          this.$message({
            type: 'success',
            message: '添加成功!'
          });
          this.fetchData();
          this.dialogFormVisible=false;
        });
      }
    },
    addUser(){
      this.resetForm();
      this.dialogFormVisible=true;
    },
    editUser(row){
      this.addUser();
      this.form=JSON.parse(JSON.stringify(row));
    },
    sizeChange(val){
      this.page=1;
      this.limit=val;
      this.fetchData();
    },
    currentChange(val){
      this.page=val;
      this.fetchData();
    },
    onSubmit(){
      this.page=1;
      this.fetchData();
    },
    async doAssign() {
      await api.doAssign(this.roleForm);
      this.$message({
        type: 'success',
        message: '成功!'
      });
      this.dialogRoleVisible=false;
    },
    async toAssign(row) {
      let data = await api.toAssign(row.id);
      this.allRoles= data.allRoles;
      this.roleForm.roleIdList= data.userRoleIds;
      this.dialogRoleVisible=true;
      this.roleForm.userId=row.id;
      this.roleForm.username=row.name;
      console.log(data)
    },
    deleteUser(id){
      this.$confirm('此操作将永久删除, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await api.remove(id);
        this.$message({
          type: 'success',
          message: '删除成功!'
        });
        this.fetchData();
      }).catch(() => {
      });
    },
    fetchData() {
      this.listLoading = true
      console.log(this.queryTime,this.query)
      if (this.queryTime){
        this.query.createTimeBegin=this.queryTime[0];
        this.query.createTimeEnd=this.queryTime[1];
      }else {
        this.query.createTimeBegin='';
        this.query.createTimeEnd=''
      }
      api.getPageList(this.page,this.limit,this.query).then(response => {
        this.list = response.records
        this.total= response.total
        this.listLoading = false
      })
    }
  }
}
</script>
